package cn.wokoba.service.activity.service.trial.node;

import cn.wokoba.service.activity.model.entity.MarketProductEntity;
import cn.wokoba.service.activity.model.entity.TrialBalanceEntity;
import cn.wokoba.service.activity.model.valobj.GroupBuyActivityDiscountVO;
import cn.wokoba.service.activity.model.valobj.SkuVO;
import cn.wokoba.service.activity.service.discount.IDiscountCalculateService;
import cn.wokoba.service.activity.service.trial.AbstractGroupBuyMarketSupport;
import cn.wokoba.service.activity.service.trial.factory.DefaultActivityStrategyFactory;
import cn.wokoba.types.desgin.framework.tree.IStrategyHandler;
import cn.wokoba.types.enums.ResponseCode;
import cn.wokoba.types.exception.AppException;
import com.alibaba.fastjson.JSON;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

@Service
@Slf4j
public class MarketNode extends AbstractGroupBuyMarketSupport {
    @Resource
    private EndNode endNode;
    @Resource
    private ErrorNode errorNode;
    @Resource
    private Map<String, IDiscountCalculateService> discountCalculateServiceMap;



    @Override
    protected TrialBalanceEntity doApply(MarketProductEntity requestParameter, DefaultActivityStrategyFactory.DynamicContext dynamicContext) throws Exception {
        log.info("拼团商品查询试算服务-MarketNode userId:{} requestParameter:{}", requestParameter.getUserId(), JSON.toJSONString(requestParameter));
        GroupBuyActivityDiscountVO groupBuyActivityDiscountVO = dynamicContext.getGroupBuyActivityDiscountVO();

        GroupBuyActivityDiscountVO.GroupBuyDiscount groupBuyDiscount = groupBuyActivityDiscountVO.getGroupBuyDiscount();
        SkuVO skuVO = dynamicContext.getSkuVO();

        IDiscountCalculateService discountCalculateService = discountCalculateServiceMap.get(groupBuyDiscount.getMarketPlan());
        if (null == discountCalculateService) {
            log.info("不存在{}类型的折扣计算服务", groupBuyDiscount.getMarketPlan());
            throw new AppException(ResponseCode.E0001.getCode(), ResponseCode.E0001.getInfo());
        }

        BigDecimal payPrice = discountCalculateService.calculate(requestParameter.getUserId(), skuVO.getOriginalPrice(), groupBuyDiscount);
        dynamicContext.setDeductionPrice(skuVO.getOriginalPrice().subtract(payPrice));
        dynamicContext.setPayPrice(payPrice);

        return router(requestParameter, dynamicContext);
    }

    @Override
    public IStrategyHandler<MarketProductEntity, DefaultActivityStrategyFactory.DynamicContext, TrialBalanceEntity> get(MarketProductEntity requestParameter, DefaultActivityStrategyFactory.DynamicContext dynamicContext) throws Exception {
        if(dynamicContext.getDeductionPrice()==null){
            return errorNode;
        }
        return endNode;
    }
}
